import dayjs from 'dayjs'
import { useMemberStore } from '@/stores'
import { getCityByLocationApi } from '@/services/location'
var DELAY_TIME = 10

/**
 * @description 日期格式处理: 两个参数都为空时返回当前日期 2000-01-01
 * @param {String} date 默认当前日期
 * @param {String} format 默认格式 'YYYY-MM-DD'
 * @return {String} 格式化后的日期
 * @example formatDate()                       获取当前日期 格式为 YYYY-MM-DD
 * @example formatDate(formatDate(), 'MM-DD')  获取当前日期 格式为 MM-DD
 * @example formatDate(formatDate(), 'DD')     获取当前日期 格式为 DD
 */
export const formatDate = (date = dayjs().format('YYYY-MM-DD'), format = 'YYYY-MM-DD') =>
  dayjs(date).format(format)

/**
 * @description 获取当前时间戳
 * @return {Number} 时间戳
 * @param {String} date 日期转换为时间戳 默认当前日期
 * @example getTimestamp()
 */
export const getTimestamp = (date: string) =>
  date ? new Date(date).getTime() : new Date().getTime()

/**
 * @description 跳转路由 没登录跳转到登录页
 * @param {string} url  路径
 * @param {Boolean} check 跳转是否需要登录
 * @param {Function} callback 回调 显示登录
 * @returns void
 * @example navigateTo('/pages-user/login/index')
 */
export const navigateTo = (url: string, check?: boolean | number, callback?: Function) => {
  if (!url) {
    throw new Error('=========== navigateTo-ERROR: 跳转路径为空 =========== ')
  } else {
    _CHECK_ERROR(() => {
      // const userStore = useMemberStore()
      // const token = userStore.token

      // if (check && !token) {
      //   callback && callback()
      //   setTimeout(() => {
      //     uni.navigateTo({ url: '/pages-user/login-page/login' })
      //   }, DELAY_TIME)
      //   return
      // }
      uni.navigateTo({ 
      	url
      })
    }, 'navigateTo-ERROR:')
  }
}

/**
 * @description 关闭所有页面，打开到应用内的某个页面。
 * @param {string} url  路径
 */
export const reLaunch = (url: string) => {
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.reLaunch({ url })
    }, DELAY_TIME)
  }, 'reLaunch-ERROR:')
}

/**
 * @description 跳转返回上一页
 * @param {Number} delta 返回的页面数
 * @return void
 * @example navigateBack(1)
 */
export const navigateBack = (delta = 1) => {
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.navigateBack({ delta })
    }, DELAY_TIME)
  }, 'navigateBack-ERROR:')
}

/**
 * @description 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
 * @param {string} url 路径
 * @return void
 * @example switchTab('/pages/index/index')
 */
export const switchTab = (url: string) => {
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.switchTab({ url })
    }, DELAY_TIME)
  }, 'switchTab-ERROR:')
}

/**
 * @description 跳转到新页面，并删除当前页面
 * @param {string} url 路径
 * @return void
 * @example redirectTo('/pages/index/index')
 */
export const redirectTo = (url: string) => {
  console.log(url)
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.redirectTo({ url })
    }, DELAY_TIME)
  }, 'redirectTo-ERROR:')
}

/**
 * @description 吐司提升
 * @param {string} title 标题
 * @param {string} icon icon默认无
 * @param {Boolean} mask 默认无
 * @param {Number} duration 1000ms
 * @return void
 * @example showToast('提示信息')
 */
export const showToast = (title: string, icon: string = 'none', mask = false, duration = 1500) => {
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.showToast({
        title,
        icon: icon as any,
        duration,
        mask,
      })
    }, DELAY_TIME)
  }, 'showToast-ERROR:')
}

/**
 * @description 显示模态弹窗
 * @param title 标题
 * @param content 内容
 * @param confirmText 确认按钮文字
 * @param cancelText 取消按钮文字
 * @param showCancel 是否显示取消按钮
 * @example  showModal({ title: '提示', content: '确定删除订单吗？' }, () => { console.log('确定') }, () => { console.log('取消') })
 */
export const showModal = (
  options: {
    title: string
    content: string
    confirmText: string
    cancelText: string
    showCancel: true
  },
  successCallback: any,
  failCallback?: any,
) => {
  const { title, content, confirmText, cancelText, showCancel } = options
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.showModal({
        title: title || '',
        content: content || '',
        confirmText: confirmText || '确定',
        cancelText: cancelText || '取消',
        showCancel,
        success(res) {
          res.confirm ? successCallback && successCallback() : failCallback && failCallback()
        },
        fail() {
          failCallback && failCallback()
        },
      })
    }, DELAY_TIME)
  }, 'showModal-ERROR:')
}

/**
 * @description 显示 loading提示框
 * @param {String} title 提示的内容
 * @return void
 * @example showLoading()
 */
export const showLoading = (title: string = '加载中...', mask: boolean = true) => {
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.showLoading({ title, mask })
    }, DELAY_TIME)
  }, 'navigateBack-ERROR:')
}

/**
 * @description 隐藏 loading提示框
 * @return void
 * @example hideLoading()
 */
export const hideLoading = () => {
  _CHECK_ERROR(() => {
    setTimeout(() => {
      uni.hideLoading()
    }, DELAY_TIME)
  }, 'navigateBack-ERROR:')
}

/**
 * @description 数据总条数转换为页数
 * @param {Number} total 总条数
 * @param {Number} pageSize 每页条数
 * @return {Number} 页数
 * @example totalToPage(100, 10) // 10
 */
export const totalToPage = (total: any, pageSize: any) =>
  Math.ceil(Number(total) / Number(pageSize))

/**
 * @description 校验手机号
 * @param {string} phone 手机号
 * @return {Boolean} true or false
 * @example checkPhone('12345678901') // false
 */
export const checkPhone = (phone: string = '') => {
  if (phone.includes('122')) return true
  return /^1[3456789]\d{9}$/.test(phone)
}

/**
 * @description 手机号脱敏
 * @param {string} phone 手机号
 * @return {string} 123****7890
 * @example phoneDesensitization('12345678901') // 123****7890
 */
export const phoneDesensitization = (phone: string = '') =>
  phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')

/**
 * @description 身份证号脱敏
 * @param {string} idCard 身份证号
 * @return {string} 123****7890
 * @example idCardDesensitization('123456789123456789') // 1234****6789
 */
export const idCardDesensitization = (idCard: string = '') =>
  idCard.replace(/^(.{6})(?:\d+)(.{4})$/, '$1******$2')

/**
 * @description 姓名脱敏
 * @param {string} name 姓名
 */
export const nameDesensitization = (name: string = '') =>
  name.replace(/^(.).*(.)$/, (_, $1, $2) => (name.length > 2 ? `${$1}**` : `*${$2}`))

/**
 * @description 图片预览
 * @param {string or array} url 当前显示图片的http[s]链接
 * @return void
 * @example previewImage('https://xxx.com/xxx.jpg')
 */
export const previewImage = (url: string | string[]) => {
  _CHECK_ERROR(() => {
    uni.previewImage({
      indicator: 'none',
      urls: Array.isArray(url) ? url : [url],
    })
  }, 'previewImage-ERROR:')
}

/**
 * @description 经纬度转省市区
 * @param {string} latitude 纬度
 * @param {string} longitude 经度
 */
export const geocoder = (latitude: string, longitude: string) =>
  getCityByLocationApi({ latitude, longitude })

/**
 * 跳转系统授权管理页
 */
export const openAppSetting = () => {
  _CHECK_ERROR(() => {
    /* #ifndef APP-PLUS */
    uni.openAppAuthorizeSetting()
    /* #endif */
  }, 'openSetting-ERROR:')
}

/**
 * 获取 APP 授权设置
 */
export const getAppSetting = () => {
  _CHECK_ERROR(() => {
    /* #ifndef APP-PLUS */
    const settingInfo = uni.getAppAuthorizeSetting()
    log('UTILS - RESPONSE - 授权设置 : ', settingInfo)
    return settingInfo
    /* #endif */
  }, 'getSetting-ERROR:')
}

/**
 * @description 设置页面标题
 * @title 页面标题
 * @return void
 * @example setNavigationBarTitle('页面标题')
 */
export const setNavBarTitle = (title: string) => {
  _CHECK_ERROR(() => {
    uni.setNavigationBarTitle({ title })
  }, 'setNavBarTitle-ERROR:')
}

/**
 * @description 拨打电话
 */
export const makePhoneCall = (phoneNumber: string | number) => {
  _CHECK_ERROR(() => {
    // #ifdef APP-PLUS
    uni.makePhoneCall({ phoneNumber: phoneNumber.toString() })
    // #endif
    // #ifndef H5
    showToast('请使用手机拨打电话')
    // #endif
  }, 'makePhoneCall-ERROR:')
}

/**
 * @description log
 * @param {string} msg 打印的信息
 * @return void
 * @axample log('打印的信息')
 */
export function log(...msg: any[]) {
  _CHECK_ERROR(() => {
    console.log(...msg)
  }, 'log-ERROR:')
}

/**
 * 异步操作，处理错误并输出日志
 * @param {Function} successCallback 成功回调函数
 * @param {String} from 出错时的标识
 */
function _CHECK_ERROR(successCallback: () => void, from: string) {
  try {
    successCallback()
  } catch (error) {
    // 避免无限递归

    console.error(
      `%c------------ ${from}------------%c`,
      'background: rgb(233, 51, 35); color: #fff; border-radius: 3px 0 0 3px;padding:2px 5px',
      'background: #1475B2; color: #fff; border-radius: 0 3px 3px 0;padding:2px 5px',
      error,
    )
  }
}
